<?php

App::uses('Crud', 'Model');
App::uses('Moe', 'Model');

class Area extends Crud
{
    /**
     * Al Agregar/eliminar/actualizar las constantes de los modelos implica ir
     * y actualizar los comentarios en los campos de la tabla asociada a este modelo.
     */
    const STATUS_ENABLED = 1;
    const STATUS_DISABLED = 0;

    /**
     * Obtenemos los registros para el grid del admin
     * @return type
     */
    public function getEnabled() {
        $filters = array(
            'fields' => array(
                'name as text',
                'id as value',
                'moe_id',
            ),
            'conditions' => array(
                'status' => self::STATUS_ENABLED
            ),
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    /**
     * Obtenemos las areas habilitadas de los moes habilitados
     * @return type
     */
    public function getEnabledWithMoe() {
        $filters = array(
            'fields' => array(
                'CONCAT(m.name, "-", Area.name) as text',
                'Area.id as value',
            ),
            'joins' => array(
                array(
                    'table' => 'moes',
                    'alias' => 'm',
                    'type' => 'INNER',
                    'conditions' => array(
                        'm.id = Area.moe_id',
                        'm.status' => Moe::STATUS_ENABLED,
                    ),
                ),
            ),
            'conditions' => array(
                'Area.status' => self::STATUS_ENABLED
            ),
            'order' => array(
                'm.name ASC',
                'Area.name ASC',
            ),
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    /**
     * Obtenemos las areas por MOE, si no existe moeId obtiene todas
     * @param type $moeId
     * @return type
     */
    public function getEnabledByMoe($moeId) {
        $filters = array(
            'fields' => array(
                'id as value',
                'name as text',
                'moe_id',
                'color as color'
            ),
            'conditions' => array(
                'status' => self::STATUS_ENABLED,
                'moe_id' => $moeId,
            ),
            'order' => array(
                'name' => 'ASC'
            ),
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    /**
     * Buscamos un area por su nombre
     * @param string $name
     * @return array
     */
    public function getByName($name) {
        return $this->find('first', array('conditions' => array(
                        'name' => $name
        )));
    }

}
